package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

import static com.sky.constant.AutoFillConstant.*;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Pointcut("execution(* com.sky.mapper.*.*(..))&&@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("公共字段自动填充");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill=signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType=autoFill.value();

        Object[] args = joinPoint.getArgs();//获取所有参数，也就是拿到实体类对象，因此规定第一个参数是实体类对象
        if(args==null||args.length==0){
            return; //空指针判断
        }
        Object entity=args[0];//获得实体对象
        LocalDateTime localDateTime=LocalDateTime.now();
        Long currentId=BaseContext.getCurrentId();
        if(operationType==OperationType.INSERT){
            try {
                Method setCreateTime = entity.getClass().getDeclaredMethod(SET_CREATE_TIME, localDateTime.getClass());
                Method setCreateUser = entity.getClass().getDeclaredMethod(SET_CREATE_USER, currentId.getClass());
                Method setUpdateTime = entity.getClass().getDeclaredMethod(SET_UPDATE_TIME, localDateTime.getClass());
                Method setUpdateUser = entity.getClass().getDeclaredMethod(SET_UPDATE_USER, currentId.getClass());
                setCreateTime.invoke(entity, localDateTime);
                setCreateUser.invoke(entity,currentId);
                setUpdateTime.invoke(entity, localDateTime);
                setUpdateUser.invoke(entity, currentId);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        if(operationType==OperationType.UPDATE){
            try {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(SET_UPDATE_TIME, localDateTime.getClass());
                Method setUpdateUser = entity.getClass().getDeclaredMethod(SET_UPDATE_USER, currentId.getClass());
                setUpdateTime.invoke(entity, localDateTime);
                setUpdateUser.invoke(entity, currentId);
            }catch(Exception e){
                e.printStackTrace();
            }
        }


    }
}
